package com.itdata.common;

import java.io.IOException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class PropertiesLoader extends PropertyPlaceholderConfigurer {
	
	protected void loadProperties(Properties props) throws IOException {
		super.loadProperties(props);
		Iterator<Object> it = props.keySet().iterator();
		Map<Object, Object> plainProps = new HashMap<Object, Object>();
		while(it.hasNext()){
			String propName = it.next().toString();
			if(propName.endsWith(Constant.CIPHERTEXT_PROPS_SUFFIX)){
				String cipherValue = props.get(propName).toString();
				try {
					Key key = RsaCryptoUtil.loadKey(RsaCryptoUtil.PRIV_KEY);
					String plainText = RsaCryptoUtil.decrypt((RSAPrivateKey)key, cipherValue);
					String newPropName = propName.replace(Constant.CIPHERTEXT_PROPS_SUFFIX, "");
					plainProps.put(newPropName, plainText);
				} catch (NoSuchAlgorithmException e) {
					throw new RuntimeException(e);
				} catch (InvalidKeySpecException e) {
					throw new RuntimeException(e);
				}
			}
		}
		props.putAll(plainProps);
	}

}
